package org.v2ray.rocket.proxy.support.base

import android.os.Bundle
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import androidx.viewbinding.ViewBinding
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import org.v2ray.rocket.proxy.support.base.mvi.MviEffect
import org.v2ray.rocket.proxy.support.base.mvi.MviIntent
import org.v2ray.rocket.proxy.support.base.mvi.MviState
import org.v2ray.rocket.proxy.support.utils.showToast
import www.sanju.motiontoast.MotionToast
import www.sanju.motiontoast.MotionToastStyle

/**
 * MVI架构的基础Activity
 * @param VB ViewBinding类型
 * @param I Intent类型
 * @param S State类型
 * @param E Effect类型
 * @param VM ViewModel类型
 */
abstract class BaseActivity<VB : ViewBinding, I : MviIntent, S : MviState, E : MviEffect, VM : BaseViewModel<I, S, E>> :
    AppCompatActivity() {

    private var _binding: VB? = null
    protected val binding get() = _binding!!

    protected abstract val viewModel: VM

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        _binding = getViewBinding()
        setContentView(binding.root)

        initView()
        initObservers()
        initData()
    }

    /**
     * 获取ViewBinding
     */
    abstract fun getViewBinding(): VB

    /**
     * 初始化视图
     */
    abstract fun initView()

    /**
     * 初始化数据
     */
    abstract fun initData()

    /**
     * 初始化观察者
     */
    private fun initObservers() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                // 观察状态变化
                launch {
                    viewModel.viewState.collect { state ->
                        renderState(state)
                    }
                }

                // 观察一次性事件
                launch {
                    viewModel.effect.collect { effect ->
                        renderEffect(effect)
                    }
                }

                // 观察Toast事件
                launch {
                    viewModel.toastEvent.collect { toastEvent ->
                        withContext(Dispatchers.Main) {
                            showToast(style = toastEvent.style, message = toastEvent.message)
                        }
                    }
                }
            }
        }
    }

    /**
     * 渲染状态
     */
    abstract fun renderState(state: S)

    /**
     * 渲染一次性事件
     */
    abstract fun renderEffect(effect: E)

    /**
     * 发送Intent
     */
    protected fun setIntent(intent: I) {
        viewModel.setIntent(intent)
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
    }
} 